package com.test.moredatesouce.common.database;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author:ZhouYang
 * @Description:
 * @Date: Created in 2019/9/2 14:07
 * @Modified By：DB2数据源配置
 */
@Configuration
@MapperScan(basePackages = DataSourceDB2.PACKAGE, sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class DataSourceDB2 {

    // 精确到 slave 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.test.moredatesouce.modules.other.db2.mapper";
    static final String MAPPER_LOCATION = "classpath*:/mapper/db2/*.xml";

    @Value("${spring.datasource.ds2.url}")
    private String url;

    @Value("${spring.datasource.ds2.username}")
    private String user;

    @Value("${spring.datasource.ds2.password}")
    private String password;

    @Value("${spring.datasource.ds2.driver-class-name}")
    private String driverClass;

    @Bean(name = "slaveDataSource")
    public DataSource slaveDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager() {
        return new DataSourceTransactionManager(slaveDataSource());
    }

    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource slaveDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(slaveDataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(DataSourceDB2.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
